package com.wei.frame.net;

import com.wei.frame.BuildConfig;
import com.wei.frame.utils.L;
import com.wei.frame.utils.Preconditions;

import org.jetbrains.annotations.Nullable;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 作者:赵若位
 * 时间:2020/12/22 15:34
 * 功能:网络请求客户端
 * Test:http://v.juhe.cn/toutiao/index?type=top&key=988e51c45bbe88a33e032f8da38a61dd
 */
public class RetrofitManager {

    private static final long DELAY_TIME = 10 * 1000L;
    private static final String URL = BuildConfig.URL;
    private OkHttpClient mClient;
    private Retrofit mRetrofit;
    private RetrofitApiService mApiService;

    private RetrofitManager() {

    }

    public static final RetrofitManager getInstance() {
        return SingleHolder.sManager;
    }

    public OkHttpClient getClient() {
        if (null == mClient) {
            mClient = new OkHttpClient.Builder()
                    .writeTimeout(DELAY_TIME, TimeUnit.MILLISECONDS)
                    .readTimeout(DELAY_TIME, TimeUnit.MILLISECONDS)
                    .connectTimeout(DELAY_TIME, TimeUnit.MILLISECONDS)
                    .addInterceptor(new HttpLoggingInterceptor(s -> L.i(s))
                            .setLevel(HttpLoggingInterceptor.Level.BODY))
                    .build();
        }
        return mClient;
    }


    public Retrofit getRetrofit() {
        if (null == mRetrofit) {
            mRetrofit = new Retrofit.Builder()
                    .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(URL)
                    .client(getClient())
                    .build();
        }
        return mRetrofit;
    }

    public Retrofit getRetrofit(@Nullable String url) {
        Preconditions.checkNotNull(url, "The Http's Url is null~");
        mRetrofit = new Retrofit.Builder()
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(url)
                .client(getClient())
                .build();
        return mRetrofit;
    }

    public RetrofitApiService getApiService() {
        if (null == mApiService) {
            mApiService = getRetrofit().create(RetrofitApiService.class);
        }
        return mApiService;
    }

    /*该静态单例无需加锁，也能保证线程安全和延迟加载*/
    private static class SingleHolder {
        private static final RetrofitManager sManager = new RetrofitManager();
    }
}
